package br.com.salaodebeleza.security;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpSession;

import br.com.salaodebeleza.ws.ClienteWS;
import br.com.salaodebeleza.ws.UserLogin;

@SessionScoped
public class Login implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// @Inject
	// User user;

	@Inject
	Permissions permissions;
	
	private String username;

	private String password;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public boolean login() {

		boolean autenticado = false;
		try {
			/*Ws_soa_autenticacaoSoapProxy p = new Ws_soa_autenticacaoSoapProxy();
			DsAutenticarUsuarioResponseDsAutenticarUsuarioResult d = p.dsAutenticarUsuario(username, password, "3044");
			*/
			UserLogin usuarioLogado = new ClienteWS().loginWS(username, password, "3044");
			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
			if (usuarioLogado != null) {

				autenticado = true;

				long cdi = Long.parseLong(usuarioLogado.getCdi());
				permissions.loadUserPermissions(usuarioLogado.getCdi());

				session.setAttribute("permissions", permissions);

			} else {
				autenticado = false;
				session.setAttribute("permissions", permissions);
			}

		} catch (Exception e) {
			autenticado = false;
		}

		return autenticado;

	}

	public void logout() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		permissions = null;
		session.setAttribute("permissions", null);
		session.invalidate();

	}

	public boolean isLoggedIn() {

		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		return session.getAttribute("permissions")!= null;

	}

	public Permissions getPermissions() {
		return permissions;
	}
	
}
